<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page import="java.io.*"%>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.util.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.fileupload.FileItemIterator" %>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>
<%@ page import="org.apache.struts2.ServletActionContext" %>
<%@ page import="java.io.BufferedInputStream" %>
<%@ page import="java.io.BufferedOutputStream" %>
<%@ page import="java.text.SimpleDateFormat"%>
<%@ page import="java.io.File"%>
<%@ page import="java.io.InputStream" %>
<%@ page import="java.io.OutputStream" %>
<%@ page import="java.io.FileOutputStream" %>
<%@ page import="java.util.regex.Matcher" %>
<%@ page import="java.util.Random" %>
<%@ page import="java.util.regex.Pattern" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.util.Properties"%>
<%@ page import="cn.swust.util.DBUtil"%>
<%
Properties p = new Properties();
try {
	p.load(DBUtil.class.getResourceAsStream("/jdbc.properties"));
	
} catch (IOException e2) {
	System.out.println(DBUtil.class+"找不到数据库配置属性文件");
	e2.printStackTrace();
}
//保存文件路径
String projectPath = p.getProperty("projectpath");//工程目录
String filePath = "";//返回给前台的路径
String smallPath="productpic";//略缩图路径
String realPath = ""; //图片的绝对路径

String savepath = ""; //临时图片保存的绝对路径
String showPath = ""; //前台显示路径
//判断路径是否存在，不存在则创建
savepath = (String)session.getAttribute("savepath");
showPath = (String)session.getAttribute("showpath");
if(savepath==null||showPath==null)
{
	filePath = "allproducts";
	
    realPath = projectPath+"\\"+filePath;
	SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); // 时间格式化的格式
	String catalog = sDateFormat.format(new Date());
	realPath = realPath+"\\"+ catalog; //作为商品图片目录名称
	filePath = filePath+"/"+catalog;
	File dir = new File(realPath);
	if(!dir.isDirectory())
		dir.mkdir();
		
	session.setAttribute("savepath",realPath);//这里为绝对路径
	session.setAttribute("showpath",filePath);//相对路径
}else
{
	realPath = savepath;
	filePath = showPath;
}

File dir = new File(realPath);
if(!dir.isDirectory())
    dir.mkdir();

if(ServletFileUpload.isMultipartContent(request)){

    DiskFileItemFactory dff = new DiskFileItemFactory();
    dff.setRepository(dir);
    dff.setSizeThreshold(1024000);
    ServletFileUpload sfu = new ServletFileUpload(dff);
    FileItemIterator fii = sfu.getItemIterator(request);
    String picID = "";//生成的图片名称
    String title = "";   //图片标题
    String url = "";    //图片地址
    String fileName = "";
	String state="SUCCESS";
	
	boolean flag = true;//拷贝第一张图片到略缩图目录
    while(fii.hasNext()){
        FileItemStream fis = fii.next();

        try{
            if(!fis.isFormField() && fis.getName().length()>0){
                fileName = fis.getName();
				Pattern reg=Pattern.compile("[.]jpg|JPG|PNG|png|JPEG|jpeg|gif$");
				Matcher matcher=reg.matcher(fileName);
				if(!matcher.find()) {
					state = "文件类型不允许！";
					break;
				}
				Random r = new Random();
				int randnum = (int) (r.nextDouble() * (99999 - 10000 + 1)) + 10000; // 获取随机数，防止图片名称重复
				picID = new Date().getTime()+randnum+fileName.substring(fileName.lastIndexOf("."),fileName.length());
                url = realPath+"\\"+picID;
               //将所有上传的图片的名称保存起来
                String picsname = (String)session.getAttribute("picsname");
               	if(picsname!=null)
               	{
               		picsname=picsname +"|"+picID;
               		session.setAttribute("picsname",picsname);
               	}else{
               		session.setAttribute("picsname",picID);
               	}
                
                BufferedInputStream in = new BufferedInputStream(fis.openStream());//获得文件输入流
                FileOutputStream a = new FileOutputStream(new File(url));
                BufferedOutputStream output = new BufferedOutputStream(a);
                Streams.copy(in, output, true);//开始把文件写到你指定的上传文件夹
                if(flag&&session.getAttribute("smallpic")==null)//开始拷贝略缩图
                {
                	String picurl = smallPath+"/"+ picID;//略缩图的相对路径
                	File oldFile = new File(url);
                	if(oldFile.exists()){
                	InputStream inStream = new FileInputStream(oldFile);// 读入原文件
                	String newpath = projectPath+"\\"+smallPath+"\\"+picID;
                	FileOutputStream fs = new FileOutputStream(newpath);
                	
                    byte[] buffer = new byte[1444];
                    int length;
                    int byteread=0, bytesum = 0;
                    while ((byteread = inStream.read(buffer)) != -1) {
                     bytesum += byteread; // 字节数 文件大小
                     fs.write(buffer, 0, byteread);
                    }
                    inStream.close();
                    session.setAttribute("smallpic",picurl);
                	flag = false;
                  }
                }
            }else{
                String fname = fis.getFieldName();

                if(fname.indexOf("pictitle")!=-1){
                    BufferedInputStream in = new BufferedInputStream(fis.openStream());
                    byte c [] = new byte[10];
                    int n = 0;
                    while((n=in.read(c))!=-1){
                        title = new String(c,0,n);
                        break;
                    }
                }
            }

        }catch(Exception e){
            e.printStackTrace();
        }
    }
	title = title.replace("&", "&amp;").replace("'", "&qpos;").replace("\"", "&quot;").replace("<", "&lt;").replace(">", "&gt;");
    response.getWriter().print("{'url':'"+filePath+"/"+picID+"','title':'"+title+"','state':'"+state+"'}");
}
%>
